package com.dc.web.controller;

import com.alibaba.excel.EasyExcel;
import com.alibaba.excel.ExcelReader;
import com.alibaba.excel.read.metadata.ReadSheet;
import com.dc.Application;
import com.dc.constant.Constants;
import com.dc.constant.MessageConstant;
import com.dc.dao.*;
import com.dc.entity.*;
import com.dc.excel.listener.*;
import com.dc.excel.model.*;
import com.dc.exception.ServiceException;
import com.dc.model.AjaxResult;
import com.dc.model.EnergyMonitorBody;
import com.dc.model.EnergyMonitorChildBody;
import com.dc.service.CalibrationService;
import com.dc.service.EnergyMonitorService;
import com.dc.service.UserService;
import com.dc.utils.FileUtils;
import io.swagger.annotations.Api;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.ObjectUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.boot.system.ApplicationHome;
import org.springframework.http.HttpHeaders;
import org.springframework.http.MediaType;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.time.LocalDateTime;
import java.util.*;
import java.util.stream.Collectors;

@Api(tags = "excel导入")
@RestController
@RequestMapping("/api/excel/import")
@Slf4j
public class ImportController {

    @Resource
    private EnergyMonitorService energyMonitorService;

    @Resource
    private ShipDao shipDao;

    @Resource
    private ShipRepairDao shipRepairDao;

    @Resource
    private WorkflowShipCutDao workflowShipCutDao;

    @Resource
    private WorkflowShipCutChildDao workflowShipCutChildDao;

    @Resource
    private WorkflowShipOldDao workflowShipOldDao;

    @Resource
    private WorkflowShipWeldDao workflowShipWeldDao;

    @Resource
    private WorkflowMachinePipeDao workflowMachinePipeDao;

    @Resource
    private MaterialSolidDao materialSolidDao;

    @Resource
    private MaterialMachineDao materialMachineDao;

    @Resource
    private WorkflowTowShipOilDao workflowTowShipOilDao;

    @Resource
    private WorkflowShipSandDao workflowShipSandDao;

    @Resource
    private WorkflowHouseSandDao workflowHouseSandDao;

    @Resource
    private WorkflowWaterCleanDao workflowWaterCleanDao;

    @Resource
    private WorkflowElectricBoxDao workflowElectricBoxDao;

    @Resource
    private CalibrationShipCutDao calibrationShipCutDao;

    @Resource
    UserService userService;

    @Resource
    private DepartmentDao departmentDao;

    @Resource
    private CalibrationService calibrationService;



    // 获取模版文件
    @GetMapping("/energy")
    public AjaxResult energy(Integer type, HttpServletResponse response) {
        //这里需要注册自己定义的处理器CustomSheetWriteHandler，CustomRowWriteHandler，否则不起作用
        ApplicationHome h = new ApplicationHome(Application.class);
        File dir = h.getDir();
        String fileName = "";
        switch (type) {
            case 1:
                fileName = "船厂碳排放-集团内部-模版.xlsx";
                break;
            case 2:
                fileName = "船厂碳排放-政府核查-模版.xlsx";
                break;
            case 3:
                fileName = "单船-船体下料-模版.xlsx";
                break;
            case 4:
                fileName = "单船-船体割旧-模版.xlsx";
                break;
            case 5:
                fileName = "单船-船体焊接-模版.xlsx";
                break;
            case 6:
                fileName = "单船-机电焊接-模板.xlsx";
                break;
            case 7:
                fileName = "单船-拖轮油耗-模版.xlsx";
                break;
            case 8:
                fileName = "单船-单船-模版.xlsx";
                break;
            case 9:
                fileName = "单船-高空车-模版.xlsx";
                break;
            case 10:
                fileName = "单船-舱室及船壳喷漆-模版.xlsx";
                break;
            case 11:
                fileName = "单船-喷漆房分段喷漆-模版.xlsx";
                break;
            case 12:
                fileName = "单船-舱室打砂-模版.xlsx";
                break;
            case 13:
                fileName = "单船-打砂房分段打砂-模版.xlsx";
                break;
            case 14:
                fileName = "单船-超水除锈-模板.xlsx";
                break;
            case 15:
                fileName = "单船-移动电箱-模板.xlsx";
                break;
            default:
                throw new ServiceException("模版类型错误，type = " + type);
        }

        String realPath = dir + File.separator + "template" + File.separator + "导入模版" + File.separator + fileName;
        try {
            response.setContentType(MediaType.APPLICATION_OCTET_STREAM_VALUE);
            FileUtils.setAttachmentResponseHeader(response, fileName);
            FileUtils.writeBytes(realPath, response.getOutputStream());
            return AjaxResult.success(realPath);
        } catch (Exception e) {
            throw new ServiceException(e.getMessage());
        }
    }
    //E:\changyun\server\target\classes\template\导入模版\物量材料模板.xlsx
    //E:\changyun\server\target\classes\template\导入模版\船厂碳排放-政府核查-模版.xlsx


    // 获取模版文件
    @GetMapping("/standard")
    public AjaxResult standardResearch(Integer type, HttpServletResponse response) {
        //这里需要注册自己定义的处理器CustomSheetWriteHandler，CustomRowWriteHandler，否则不起作用
        ApplicationHome h = new ApplicationHome(Application.class);
        File dir = h.getDir();
        String fileName = "";
        switch (type) {
            case 1:
                fileName = "标定研究数据-船体下料-模版.xlsx";
                break;
            case 2:
                fileName = "船厂碳排放-政府核查-模版.xlsx";
                break;
            case 3:
                fileName = "单船-船体下料-模版.xlsx";
                break;
            case 4:
                fileName = "单船-船体割旧-模版.xlsx";
                break;
            case 5:
                fileName = "单船-船体焊接-模版.xlsx";
                break;
            case 6:
                fileName = "单船-机电焊接-模板.xlsx";
                break;
            case 7:
                fileName = "单船-拖轮油耗-模版.xlsx";
                break;
            case 8:
                fileName = "单船-单船-模版.xlsx";
                break;
            case 9:
                fileName = "单船-高空车-模版.xlsx";
                break;
            case 10:
                fileName = "单船-舱室及船壳喷漆-模版.xlsx";
                break;
            case 11:
                fileName = "单船-喷漆房分段喷漆-模版.xlsx";
                break;
            case 12:
                fileName = "单船-舱室打砂-模版.xlsx";
                break;
            case 13:
                fileName = "单船-打砂房分段打砂-模版.xlsx";
                break;
            default:
                throw new ServiceException("模版类型错误，type = " + type);
        }

        String realPath = dir + File.separator + "template" + File.separator + "导入模版" + File.separator + fileName;
        try {
            response.setContentType(MediaType.APPLICATION_OCTET_STREAM_VALUE);
            FileUtils.setAttachmentResponseHeader(response, fileName);
            FileUtils.writeBytes(realPath, response.getOutputStream());
            return AjaxResult.success(realPath);
        } catch (Exception e) {
            throw new ServiceException(e.getMessage());
        }
    }

    // 获取模版文件
    @GetMapping("/material")
    public AjaxResult material(Integer type, HttpServletResponse response) {
        //这里需要注册自己定义的处理器CustomSheetWriteHandler，CustomRowWriteHandler，否则不起作用
        ApplicationHome h = new ApplicationHome(Application.class);
        File dir = h.getDir();
        String fileName = "";
        switch (type) {
            case 1:
                fileName = "material-solid.xlsx";
                //fileName = "船厂碳排放-集团内部-模版.xlsx";
                break;
            case 2:
                fileName = "material-machine.xlsx";
                break;
            default:
                throw new ServiceException("模版类型错误，type = " + type);
        }

        String realPath = dir + File.separator + "template" + File.separator + "导入模版" + File.separator + fileName;
        try {
            response.setContentType(MediaType.APPLICATION_OCTET_STREAM_VALUE);
            FileUtils.setAttachmentResponseHeader(response, fileName);
            FileUtils.writeBytes(realPath, response.getOutputStream());
            return AjaxResult.success(realPath);
        } catch (Exception e) {
            throw new ServiceException(e.getMessage());
        }
    }

    // 船厂碳排放  导入
    @PostMapping("/energy")
    public AjaxResult uploadCountryCuConfig(@RequestParam("company") String company,
                                            @RequestParam("type") Integer type,
                                            @RequestParam("year") Integer year,
                                            @RequestParam("file") MultipartFile file){
        return energy(company, type, year, file);
    }

    // 单船 导入
    // 1.船体下料 导入
    @PostMapping("/ship_cut")
    public AjaxResult shipCut(@RequestParam("shipRepairId") Long shipRepairId, @RequestParam("file") MultipartFile file){

        if (file.isEmpty()){
            return AjaxResult.error("上传文件为空!");
        }

        try {
            WorkflowShipCutExcelListener readListener = new WorkflowShipCutExcelListener();
            ExcelReader excelReader = EasyExcel.read(file.getInputStream(), WorkflowShipCutModel.class, readListener).headRowNumber(2).build();
            ReadSheet readSheet = EasyExcel.readSheet(0).build();
            excelReader.read(readSheet);
            List<WorkflowShipCutModel> results = readListener.getResults();
            excelReader.finish();

            if(ObjectUtils.isNotEmpty(results)) {

                // 维修单
                Optional<ShipRepairEntity> optionalShipRepair = shipRepairDao.findById(shipRepairId);
                if(!optionalShipRepair.isPresent()) {
                    throw new ServiceException(MessageConstant.ERR_SHIP_REPAIR_MISSING);
                }

                ShipRepairEntity shipRepairEntity = optionalShipRepair.get();

                Map<String, List<WorkflowShipCutModel>> map = results.stream().collect(Collectors.groupingBy(t -> t.getRoom() + "_" + t.getWeight() + "_" + t.getShipWeight(), Collectors.toList()));

                for (Map.Entry<String, List<WorkflowShipCutModel>> entry : map.entrySet()) {
                    if("null_null_null".equals(entry.getKey())) {       // 如果读取 room_weight_shipWeight 都为 null， 则数据不要
                        continue;
                    }
                    List<WorkflowShipCutModel> modelList = entry.getValue();
                    WorkflowShipCutModel model = modelList.get(0);
                    WorkflowShipCutEntity entity = new WorkflowShipCutEntity();
                    entity.setRoom(model.getRoom());
                    entity.setWeight(model.getWeight());
                    entity.setShipWeight(model.getShipWeight());
                    entity.setShipRepairEntity(shipRepairEntity);
                    WorkflowShipCutEntity save = workflowShipCutDao.save(entity);

                    List<WorkflowShipCutChildEntity> childEntityList = modelList.stream().map(t -> {
                        WorkflowShipCutChildEntity child = new WorkflowShipCutChildEntity();
                        child.setDeviceNo(model.getDevice());
                        child.setMfid(model.getMfid());
                        child.setStartTime(model.getStartTime());
                        child.setEndTime(model.getEndTime());
                        child.setTotalPower(0.);
                        child.setWorkflowShipCutEntity(save);

                        return child;

                    }).collect(Collectors.toList());

                    workflowShipCutChildDao.saveAll(childEntityList);
                }

            }

            return AjaxResult.success(results);
        } catch (Exception e) {
            return AjaxResult.error(e.getMessage());
        }
    }


    // 2. 船体割旧 导入
    @PostMapping("/ship_old")
    public AjaxResult shipOld(@RequestParam("shipRepairId") Long shipRepairId, @RequestParam("file") MultipartFile file) {

        if (file.isEmpty()){
            return AjaxResult.error("上传文件为空!");
        }

        Optional<ShipRepairEntity> optionalShipRepair = shipRepairDao.findById(shipRepairId);
        if(!optionalShipRepair.isPresent()) {
            throw new ServiceException(MessageConstant.ERR_SHIP_REPAIR_MISSING);
        }
        ShipRepairEntity shipRepairEntity = optionalShipRepair.get();

        Date date = new Date();

        try {
            WorkflowShipOldExcelListener readListener = new WorkflowShipOldExcelListener();
            ExcelReader excelReader = EasyExcel.read(file.getInputStream(), WorkflowShipOldModel.class, readListener).headRowNumber(2).build();
            ReadSheet readSheet = EasyExcel.readSheet(0).build();
            excelReader.read(readSheet);
            List<WorkflowShipOldModel> results = readListener.getResults();
            excelReader.finish();

            if(ObjectUtils.isNotEmpty(results)) {
                List<WorkflowShipOldEntity> entityList = results.stream().map(t -> {
                    WorkflowShipOldEntity entity = new WorkflowShipOldEntity();
                    entity.setRoom(t.getRoom());
                    entity.setLength(t.getLength());
                    entity.setNum(t.getNum());
                    entity.setSubmitTime(date);
                    entity.setThickness(t.getThickness());
                    entity.setType(t.getType());
                    entity.setWidth(t.getWidth());
                    entity.setShipRepairEntity(shipRepairEntity);
                    return entity;
                }).collect(Collectors.toList());

                workflowShipOldDao.saveAll(entityList);

            }

            return AjaxResult.success(results);
        } catch (Exception e) {
            return AjaxResult.error(e.getMessage());
        }
    }

    // 3. 船体焊接 导入
    @PostMapping("/ship_weld")
    public AjaxResult shipWeld(@RequestParam("shipRepairId") Long shipRepairId, @RequestParam("file") MultipartFile file) {

        if (file.isEmpty()){
            return AjaxResult.error("上传文件为空!");
        }

        Optional<ShipRepairEntity> optionalShipRepair = shipRepairDao.findById(shipRepairId);
        if(!optionalShipRepair.isPresent()) {
            throw new ServiceException(MessageConstant.ERR_SHIP_REPAIR_MISSING);
        }
        ShipRepairEntity shipRepairEntity = optionalShipRepair.get();

        Date date = new Date();

        try {
            WorkflowShipWeldExcelListener readListener = new WorkflowShipWeldExcelListener();
            ExcelReader excelReader = EasyExcel.read(file.getInputStream(), WorkflowShipWeldModel.class, readListener).headRowNumber(2).build();
            ReadSheet readSheet = EasyExcel.readSheet(0).build();
            excelReader.read(readSheet);
            List<WorkflowShipWeldModel> results = readListener.getResults();
            excelReader.finish();

            if(ObjectUtils.isNotEmpty(results)) {
                List<WorkflowShipWeldEntity> entityList = results.stream().map(t -> {
                    WorkflowShipWeldEntity entity = new WorkflowShipWeldEntity();
                    // 设置值
                    entity.setSubmitTime(date);
                    entity.setRoom(t.getRoom());
                    entity.setWeldType(t.getWeldType());
                    entity.setBoardType(t.getBoardType());
                    entity.setLength(t.getLength());
                    entity.setThickness(t.getThickness());
                    entity.setWidth(t.getWidth());
                    entity.setNum(t.getNum());

                    entity.setShipRepairEntity(shipRepairEntity);
                    return entity;
                }).collect(Collectors.toList());

                workflowShipWeldDao.saveAll(entityList);
            }
            return AjaxResult.success(results);
        } catch (Exception e) {
            return AjaxResult.error(e.getMessage());
        }
    }

    // 4. 机电焊接
    @PostMapping("/machine_pipe")
    public AjaxResult machinePipe(@RequestParam("shipRepairId") Long shipRepairId, @RequestParam("file") MultipartFile file) {

        if (file.isEmpty()){
            return AjaxResult.error("上传文件为空!");
        }

        Optional<ShipRepairEntity> optionalShipRepair = shipRepairDao.findById(shipRepairId);
        if(!optionalShipRepair.isPresent()) {
            throw new ServiceException(MessageConstant.ERR_SHIP_REPAIR_MISSING);
        }
        ShipRepairEntity shipRepairEntity = optionalShipRepair.get();

        Date date = new Date();

        try {
            WorkflowMachinePipeExcelListener readListener = new WorkflowMachinePipeExcelListener();
            ExcelReader excelReader = EasyExcel.read(file.getInputStream(), WorkflowMachinePipeModel.class, readListener).headRowNumber(2).build();
            ReadSheet readSheet = EasyExcel.readSheet(0).build();
            excelReader.read(readSheet);
            List<WorkflowMachinePipeModel> results = readListener.getResults();
            excelReader.finish();

            if(ObjectUtils.isNotEmpty(results)) {
                List<WorkflowMachinePipeEntity> entityList = results.stream().map(t -> {
                    WorkflowMachinePipeEntity entity = new WorkflowMachinePipeEntity();
                    // 设置值
                    entity.setSubmitTime(date);
                    entity.setRoom(t.getRoom());
                    entity.setDevice(t.getDevice());
                    entity.setDiam(t.getDiam());
                    entity.setZgNum(t.getZgNum());
                    entity.setWgNum(t.getWgNum());
                    entity.setFlNum(t.getFlNum());
                    entity.setTgNum(t.getTgNum());

                    entity.setShipRepairEntity(shipRepairEntity);
                    return entity;
                }).collect(Collectors.toList());

                workflowMachinePipeDao.saveAll(entityList);
            }
            return AjaxResult.success(results);
        } catch (Exception e) {
            return AjaxResult.error(e.getMessage());
        }
    }

    // 4. 拖轮油耗
    @PostMapping("/tow_ship_oil")
    public AjaxResult towShipOil(@RequestParam("shipRepairId") Long shipRepairId, @RequestParam("file") MultipartFile file) {

        if (file.isEmpty()){
            return AjaxResult.error("上传文件为空!");
        }

        Optional<ShipRepairEntity> optionalShipRepair = shipRepairDao.findById(shipRepairId);
        if(!optionalShipRepair.isPresent()) {
            throw new ServiceException(MessageConstant.ERR_SHIP_REPAIR_MISSING);
        }
        ShipRepairEntity shipRepairEntity = optionalShipRepair.get();

        Date date = new Date();

        try {
            WorkflowTowShipOilListener readListener = new WorkflowTowShipOilListener();
            ExcelReader excelReader = EasyExcel.read(file.getInputStream(), WorkflowTowShipOilModel.class, readListener).headRowNumber(2).build();
            ReadSheet readSheet = EasyExcel.readSheet(0).build();
            excelReader.read(readSheet);
            List<WorkflowTowShipOilModel> results = readListener.getResults();
            excelReader.finish();

            if(ObjectUtils.isNotEmpty(results)) {
                List<WorkflowTowShipOilEntity> entityList = results.stream().map(t -> {
                    WorkflowTowShipOilEntity entity = new WorkflowTowShipOilEntity();
                    // 设置值
                    entity.setSubmitTime(date);
                    entity.setRoom(t.getRoom());
                    entity.setType(t.getType());
                    entity.setTug(t.getTug());
                    entity.setTugPower(t.getTugPower());
                    entity.setOil(t.getOil());
                    entity.setStartTime(t.getStartTime());
                    entity.setEndTime(t.getEndTime());
                    entity.setStartPlace(t.getStartPlace());
                    entity.setEndPlace(t.getEndPlace());
                    entity.setRemark(t.getRemark());

                    entity.setShipRepairEntity(shipRepairEntity);
                    return entity;
                }).collect(Collectors.toList());

                workflowTowShipOilDao.saveAll(entityList);
            }
            return AjaxResult.success(results);
        } catch (Exception e) {
            return AjaxResult.error(e.getMessage());
        }
    }

    // 12. 舱室打砂
    @PostMapping("/ship_sand")
    public AjaxResult shipSand(@RequestParam("shipRepairId") Long shipRepairId, @RequestParam("file") MultipartFile file) {

        if (file.isEmpty()){
            return AjaxResult.error("上传文件为空!");
        }

        Optional<ShipRepairEntity> optionalShipRepair = shipRepairDao.findById(shipRepairId);
        if(!optionalShipRepair.isPresent()) {
            throw new ServiceException(MessageConstant.ERR_SHIP_REPAIR_MISSING);
        }
        ShipRepairEntity shipRepairEntity = optionalShipRepair.get();

        Date date = new Date();

        try {
            WorkflowShipSandExcelListener readListener = new WorkflowShipSandExcelListener();
            ExcelReader excelReader = EasyExcel.read(file.getInputStream(), WorkflowShipSandModel.class, readListener).headRowNumber(2).build();
            ReadSheet readSheet = EasyExcel.readSheet(0).build();
            excelReader.read(readSheet);
            List<WorkflowShipSandModel> results = readListener.getResult();
            excelReader.finish();

            if(ObjectUtils.isNotEmpty(results)) {
                List<WorkflowShipSandEntity> entityList = results.stream().map(t -> {
                    WorkflowShipSandEntity entity = new WorkflowShipSandEntity();
                    // 设置值
                    entity.setSubmitTime(date);
                    entity.setRoom(t.getRoom());
                    entity.setArea(t.getArea());
                    entity.setPlace(t.getPlace());
                    entity.setStartTime(t.getStartTime());
                    entity.setEndTime(t.getEndTime());
                    entity.setShipRepairEntity(shipRepairEntity);
                    return entity;
                }).collect(Collectors.toList());

                workflowShipSandDao.saveAll(entityList);
            }
            return AjaxResult.success(results);
        } catch (Exception e) {
            return AjaxResult.error(e.getMessage());
        }
    }




    //13 打砂房分段打砂
    @PostMapping("/house_sand")
    public AjaxResult houseSand(@RequestParam("shipRepairId") Long shipRepairId, @RequestParam("file") MultipartFile file) {

        if (file.isEmpty()){
            return AjaxResult.error("上传文件为空!");
        }

        Optional<ShipRepairEntity> optionalShipRepair = shipRepairDao.findById(shipRepairId);
        if(!optionalShipRepair.isPresent()) {
            throw new ServiceException(MessageConstant.ERR_SHIP_REPAIR_MISSING);
        }
        ShipRepairEntity shipRepairEntity = optionalShipRepair.get();

        Date date = new Date();

        try {
            WorkflowHouseSandExcelListener readListener = new WorkflowHouseSandExcelListener();
            ExcelReader excelReader = EasyExcel.read(file.getInputStream(), WorkflowHouseSandModel.class, readListener).headRowNumber(2).build();
            ReadSheet readSheet = EasyExcel.readSheet(0).build();
            excelReader.read(readSheet);
            List<WorkflowHouseSandModel> results = readListener.getResults();
            excelReader.finish();

            if(ObjectUtils.isNotEmpty(results)) {
                List<WorkflowHouseSandEntity> entityList = results.stream().map(t -> {
                    WorkflowHouseSandEntity entity = new WorkflowHouseSandEntity();
                    // 设置值
                    entity.setSubmitTime(date);
                    entity.setRoom(t.getRoom());
                    entity.setArea(t.getArea());
                    entity.setProject(t.getProject());
                    entity.setShipRepairEntity(shipRepairEntity);
                    return entity;
                }).collect(Collectors.toList());

                workflowHouseSandDao.saveAll(entityList);
            }
            return AjaxResult.success(results);
        } catch (Exception e) {
            return AjaxResult.error(e.getMessage());
        }
    }

    // 14.超水除锈
    @PostMapping("/water_clean")
    public AjaxResult waterClean(@RequestParam("shipRepairId") Long shipRepairId, @RequestParam("file") MultipartFile file) {

        if (file.isEmpty()){
            return AjaxResult.error("上传文件为空!");
        }

        Optional<ShipRepairEntity> optionalShipRepair = shipRepairDao.findById(shipRepairId);
        if(!optionalShipRepair.isPresent()) {
            throw new ServiceException(MessageConstant.ERR_SHIP_REPAIR_MISSING);
        }
        ShipRepairEntity shipRepairEntity = optionalShipRepair.get();

        Date date = new Date();

        try {
            WorkflowWaterCleanExcelListener readListener = new WorkflowWaterCleanExcelListener();
            ExcelReader excelReader = EasyExcel.read(file.getInputStream(), WorkflowWaterCleanModel.class, readListener).headRowNumber(2).build();
            ReadSheet readSheet = EasyExcel.readSheet(0).build();
            excelReader.read(readSheet);
            List<WorkflowWaterCleanModel> results = readListener.getResultList();
            excelReader.finish();

            if(ObjectUtils.isNotEmpty(results)) {
                List<WorkflowWaterCleanEntity> entityList = results.stream().map(t -> {
                    WorkflowWaterCleanEntity entity = new WorkflowWaterCleanEntity();
                    // 设置值
                    entity.setSubmitTime(date);
                    entity.setRoom(t.getRoom());
                    entity.setType(t.getType());
                    entity.setArea(t.getArea());
                    entity.setPlace(t.getPlace());
                    entity.setShipRepairEntity(shipRepairEntity);
                    return entity;
                }).collect(Collectors.toList());

                workflowWaterCleanDao.saveAll(entityList);
            }
            return AjaxResult.success(results);
        } catch (Exception e) {
            return AjaxResult.error(e.getMessage());
        }
    }


    // 15.移动电箱
    @PostMapping("/electric_box")
    public AjaxResult electricBox(@RequestParam("shipRepairId") Long shipRepairId, @RequestParam("file") MultipartFile file) {
        //到447行都不用改
        if (file.isEmpty()){
            return AjaxResult.error("上传文件为空!");
        }

        Optional<ShipRepairEntity> optionalShipRepair = shipRepairDao.findById(shipRepairId);
        if(!optionalShipRepair.isPresent()) {
            throw new ServiceException(MessageConstant.ERR_SHIP_REPAIR_MISSING);
        }
        ShipRepairEntity shipRepairEntity = optionalShipRepair.get();

        Date date = new Date();

        //try catch代码块里把Listener相关的代码替换为自己的model和entity即可
        try {
            //todo 这里要换一下listener
            WorkflowElectricBoxListener readListener = new WorkflowElectricBoxListener();
            //todo 这里要换一下Model.class
            ExcelReader excelReader = EasyExcel.read(file.getInputStream(), WorkflowElectricBoxModel.class, readListener).headRowNumber(2).build();
            ReadSheet readSheet = EasyExcel.readSheet(0).build();
            excelReader.read(readSheet);
            List<WorkflowElectricBoxModel> results = readListener.getResults();
            excelReader.finish();

            if(ObjectUtils.isNotEmpty(results)) {
                //todo  List<>里的类要改成对应的entity实体类
                List<WorkflowElectricBoxEntity> entityList = results.stream().map(t -> {
                    // todo entity实例里要改成对应的entity实体类
                    WorkflowElectricBoxEntity entity = new WorkflowElectricBoxEntity();
                    // todo 设置值
                    //entity.setSubmitTime(date);
                    entity.setRoom(t.getRoom());
                    entity.setElectricBoxNo(t.getElectricBoxNo());
                    entity.setMfid(t.getMfid());

                    entity.setShipRepairEntity(shipRepairEntity);
                    return entity;
                }).collect(Collectors.toList());

                //todo 改成我们自己的dao类，改之前要在这个contoller头部引入一下 @Resource WorkflowElectricBoxDao workflowElectricBoxDao
                workflowElectricBoxDao.saveAll(entityList);
            }
            return AjaxResult.success(results);
        } catch (Exception e) {
            return AjaxResult.error(e.getMessage());
        }
    }


    // 4.
    @PostMapping("/solid")
    public AjaxResult materialSolid(@RequestParam("shipRepairId") Long shipRepairId, @RequestParam("file") MultipartFile file) {

        if (file.isEmpty()){
            return AjaxResult.error("上传文件为空!");
        }

        Optional<ShipRepairEntity> optionalShipRepair = shipRepairDao.findById(shipRepairId);
        if(!optionalShipRepair.isPresent()) {
            throw new ServiceException(MessageConstant.ERR_SHIP_REPAIR_MISSING);
        }
        ShipRepairEntity shipRepairEntity = optionalShipRepair.get();

        try {
            MaterialSolidListener readListener = new MaterialSolidListener();
            ExcelReader excelReader = EasyExcel.read(file.getInputStream(), MaterialSolidModel.class, readListener).headRowNumber(2).build();
            ReadSheet readSheet = EasyExcel.readSheet(0).build();
            excelReader.read(readSheet);
            List<MaterialSolidModel> results = readListener.getResults();
            excelReader.finish();

            if(ObjectUtils.isNotEmpty(results)) {
                List<MaterialSolidEntity> entityList = results.stream().map(t -> {
                    MaterialSolidEntity entity = new MaterialSolidEntity();
                    // 设置值
                    entity.setSubmittedTime(LocalDateTime.now());
                    entity.setSupplierUnit(t.getSupplierUnit());
                    entity.setPickingDepart(t.getPickingDepart());
                    entity.setShipRepairEntity(shipRepairEntity);
                    DepartmentEntity departmentEntity = new DepartmentEntity();
                    departmentEntity.setId(t.getDepartmentId());
                    entity.setDepartment(departmentEntity);
                    //entity.setDepartId(t.getDepartmentId());
                    entity.setTransactionType(t.getTransactionType());
                    entity.setProjectCode(t.getProjectCode());
                    entity.setProjectName(t.getProjectName());
                    entity.setMaterialCode(t.getMaterialCode());
                    entity.setMaterialCode(t.getMaterialCode());
                    entity.setMaterialName(t.getMaterialName());
                    entity.setMaterialGroup(t.getMaterialGroup());
                    entity.setShippedNum(t.getShippedNum());
                    entity.setTotalWeight(t.getTotalWeight());
                    entity.setUnit(t.getUnit());
                    entity.setUnitWeight(t.getUnitWeight());
                    entity.setBuyingCom(t.getBuyingCom());
                    entity.setSupplierCom(t.getSupplierCom());
                    //entity.setDepartId(sh);

                    return entity;
                }).collect(Collectors.toList());

                materialSolidDao.saveAll(entityList);
            }
            return AjaxResult.success(results);
        } catch (Exception e) {
            return AjaxResult.error(e.getMessage());
        }
    }

    // 4.
    @PostMapping("/machine")
    public AjaxResult materialMachine(@RequestParam("shipRepairId") Long shipRepairId, @RequestParam("file") MultipartFile file) {

        if (file.isEmpty()){
            return AjaxResult.error("上传文件为空!");
        }

        Optional<ShipRepairEntity> optionalShipRepair = shipRepairDao.findById(shipRepairId);
        if(!optionalShipRepair.isPresent()) {
            throw new ServiceException(MessageConstant.ERR_SHIP_REPAIR_MISSING);
        }
        ShipRepairEntity shipRepairEntity = optionalShipRepair.get();

        try {
            MaterialMachineListener readListener = new MaterialMachineListener();
            ExcelReader excelReader = EasyExcel.read(file.getInputStream(), MaterialMachineModel.class, readListener).headRowNumber(1).build();
            ReadSheet readSheet = EasyExcel.readSheet(0).build();
            excelReader.read(readSheet);
            List<MaterialMachineModel> results = readListener.getResults();
            excelReader.finish();

            if(ObjectUtils.isNotEmpty(results)) {
                List<MaterialMachineEntity> entityList = results.stream().map(t -> {
                    MaterialMachineEntity entity = new MaterialMachineEntity();
                    entity.setShipRepairEntity(shipRepairEntity);
                    // 设置值
                    entity.setSubmittedTime(LocalDateTime.now());
                    DepartmentEntity departmentEntity = new DepartmentEntity();
                    departmentEntity.setId(t.getDepartId());
                    entity.setDepartment(departmentEntity);
                    entity.setMachine(t.getMachine());
                    entity.setMachineCode(t.getMachineCode());
                    entity.setSupplierUnit(t.getSupplierUnit());
                    entity.setNum(t.getNum());
                    entity.setUnit(t.getUnit());
                    entity.setHours(t.getHours());

                    entity.setShipRepairEntity(shipRepairEntity);


                    return entity;
                }).collect(Collectors.toList());

                materialMachineDao.saveAll(entityList);
            }
            return AjaxResult.success(results);
        } catch (Exception e) {
            return AjaxResult.error(e.getMessage());
        }
    }


    @PostMapping("/calibration_ship_cut")
    public AjaxResult calibrationShipCut(@RequestParam("file") MultipartFile file, @RequestHeader HttpHeaders httpHeaders) {
        UserEntity user = userService.getUser(httpHeaders);
        if (file.isEmpty()){
            return AjaxResult.error("上传文件为空!");
        }
        try {
            CalibrationShipCutListener readListener = new CalibrationShipCutListener();
            ExcelReader excelReader = EasyExcel.read(file.getInputStream(), CalibrationShipCutModel.class, readListener).headRowNumber(1).build();
            ReadSheet readSheet = EasyExcel.readSheet(0).build();
            excelReader.read(readSheet);
            List<CalibrationShipCutModel> results = readListener.getResults();
            excelReader.finish();

            if(ObjectUtils.isNotEmpty(results)) {
                List<CalibrationShipCutEntity> entityList = results.stream().map(t -> {
                    CalibrationShipCutEntity entity = new CalibrationShipCutEntity();
                    // 设置值
                    Optional<ShipEntity> shipEntity = shipDao.findByName(t.getShipName());
                    BeanUtils.copyProperties(t,entity);
                    shipEntity.ifPresent(ship -> entity.setShipId(String.valueOf(ship.getId())));
                    entity.setUpdater(user.getUserName());
                    entity.setUpdateTime(new Date());
                    calibrationService.calc(entity);
                    return entity;
                }).collect(Collectors.toList());
                calibrationShipCutDao.saveAll(entityList);
            }
            return AjaxResult.success(results);
        } catch (Exception e) {
            return AjaxResult.error(e.getMessage());
        }
    }


    //// 船厂碳排放
    private AjaxResult energy(String company,
                             Integer type,
                             Integer year,
                             MultipartFile file){
        if (file.isEmpty()){
            return AjaxResult.error("上传文件为空!");
        }

        try {
            EnergyExcelListener readListener = new EnergyExcelListener();
            ExcelReader excelReader = EasyExcel.read(file.getInputStream(), EnergyModel.class, readListener).headRowNumber(2).build();
            ReadSheet readSheet = EasyExcel.readSheet(0).build();
            excelReader.read(readSheet);
            List<EnergyModel> results = readListener.getResults();
            excelReader.finish();
            System.out.println("Read results size: " + results.size()); // 调试输出
            if(ObjectUtils.isNotEmpty(results)) {

                List<EnergyMonitorChildBody> list = new ArrayList<>();

                for (EnergyModel energyModel : results) {
                    EnergyMonitorChildBody data = new EnergyMonitorChildBody();
                    data.setName(energyModel.getName());
                    data.setRatio(Constants.getRatioByEnergyType(energyModel.getName()));
                    data.setUnit(energyModel.getUnit());
                    data.setFactor(0.); // 废弃字段
                    List<Double> months = new ArrayList<>();
                    months.add(energyModel.getMonth1() == null ? 0.0 : energyModel.getMonth1());
                    months.add(energyModel.getMonth2() == null ? 0.0 : energyModel.getMonth2());
                    months.add(energyModel.getMonth3() == null ? 0.0 : energyModel.getMonth3());
                    months.add(energyModel.getMonth4() == null ? 0.0 : energyModel.getMonth4());
                    months.add(energyModel.getMonth5() == null ? 0.0 : energyModel.getMonth5());
                    months.add(energyModel.getMonth6() == null ? 0.0 : energyModel.getMonth6());
                    months.add(energyModel.getMonth7() == null ? 0.0 : energyModel.getMonth7());
                    months.add(energyModel.getMonth8() == null ? 0.0 : energyModel.getMonth8());
                    months.add(energyModel.getMonth9() == null ? 0.0 : energyModel.getMonth9());
                    months.add(energyModel.getMonth10() == null ? 0.0 : energyModel.getMonth10());
                    months.add(energyModel.getMonth11() == null ? 0.0 : energyModel.getMonth11());
                    months.add(energyModel.getMonth12() == null ? 0.0 : energyModel.getMonth12());

                    data.setMonths(months);

                    list.add(data);

                }
                EnergyMonitorBody body = new EnergyMonitorBody(company, type, year, list);

                energyMonitorService.insertOrUpdate(body);
            }

            return AjaxResult.success(results);
        } catch (Exception e) {
            return AjaxResult.error(e.getMessage());
        }
    }
}
